package webs.servlet.ServletCookie;
//通过Cookie完成身份识别（第一次访问还是第二次访问）
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/servletCookieDemo3")
public class ServletCookieDemo3 extends HttpServlet
{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        resp.setContentType("text/html;charset=utf-8");
        Cookie[] cs = req.getCookies();
        boolean flag=false;//表示Cookie中没有某一Cookie值
        if(cs!=null && cs.length>0)
        {
            for (Cookie cookie : cs)
            {
                if(cookie.getName().equalsIgnoreCase("lastTime"))
                {
                    flag=true;
                    String time=cookie.getValue();//获取上一次Cookie中的之间
                    time=URLDecoder.decode(time,"utf-8");//将时间解码操作
                    resp.getWriter().write("<h1>欢迎回来，你上一次访问时间为："+time+"</h1>");
                    setTime(cookie);
                    resp.addCookie(cookie);
                    break;
                }
            }
        }
        if(cs==null||cs.length==0||flag==false)
        {
            Date date=new Date();//获取系统当前时间
            SimpleDateFormat stf=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
            String stf_date = stf.format(date);
            //进行URL编码
            stf_date=URLEncoder.encode(stf_date,"utf-8");
            Cookie cookie=new Cookie("lastTime",stf_date);
            //设置Cookie存储时间为1小时
            cookie.setMaxAge(60*60);
            resp.getWriter().write("<h1>欢迎第一次到来！</h1>");
            resp.addCookie(cookie);
        }
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        this.doPost(req,resp);
    }
    public static void setTime(Cookie cookie) throws UnsupportedEncodingException
    {
        Date date=new Date();
        SimpleDateFormat stf=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
        String stf_date=stf.format(date);
        //进行URL编码
        stf_date = URLEncoder.encode(stf_date,"utf-8");
        cookie.setValue(stf_date);
        cookie.setMaxAge(60*60);
    }
}
